<?php

namespace App\Http\Controllers\Api\v2;


use App\Http\Controllers\ApiController;
use App\Models\Address;

class AddressController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddress()
    {
        $address_id = $this->request->input('address_id');
        if ($address_id) {
            $address = Address::find($address_id);
        }else {
            $address = Address::where('uid', $this->uid)->orderByDesc('isdefault')->first();
        }

        return ajaxReturn(['address'=>$address]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddressList()
    {
        $items = Address::where('uid', $this->uid)->orderByDesc('isdefault')->get();
        return ajaxReturn(['items'=>$items, 'total_count'=>count($items)]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefault()
    {
        $address_id = $this->request->input('address_id');
        Address::where('uid', $this->uid)->update(['isdefault'=>0]);
        Address::where(['uid'=>$this->uid, 'address_id'=>$address_id])->update(['isdefault'=>1]);
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delete()
    {
        $address_id = $this->request->input('address_id');
        Address::where(['uid'=>$this->uid, 'address_id'=>$address_id])->delete();
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function save()
    {
        $address_id = $this->request->input('address_id');
        $address = $this->request->input('address');

        if ($address['isdefault']) {
            Address::where('uid', $this->uid)->update(['isdefault'=>0]);
        }

        if ($address_id) {
            Address::where(['uid'=>$this->uid, 'address_id'=>$address_id])->update($address);
        } else {
            $address['uid'] = $this->uid;
            $address_id = Address::insertGetId($address);
        }

        return ajaxReturn(['address_id'=>$address_id]);
    }
}
